// [[ OnflowGenerator File UUID: 56321cac6ee54a7d962e2321256c0be8  ]]
package com.itdct.onflow.system.configuration.service

import com.itdct.adexcel.input.bean.ExcelInputRowBean
import com.itdct.adexcel.input.listener.RowDataListener
import com.itdct.onflow.core.constant.CommonString
import com.itdct.onflow.core.constant.ReturnCode
import com.itdct.onflow.core.extend.*
import com.itdct.onflow.core.util.KBeanCopyUtil
import com.itdct.onflow.core.vo.KeyLabelValueVo
import com.itdct.onflow.core.vo.RespPageVo
import com.itdct.onflow.core.vo.RespVo
import com.itdct.onflow.system.common.base.BaseSysService
import com.itdct.onflow.system.common.base.ImportExcelQo
import com.itdct.onflow.system.common.context.Context
import com.itdct.onflow.system.common.extend.dict
import com.itdct.onflow.system.configuration.entity.SysConfigurationEntity
import com.itdct.onflow.system.configuration.mapper.SysConfigurationMapper
import com.itdct.onflow.system.configuration.qo.SysConfigurationEditQo
import com.itdct.onflow.system.configuration.qo.SysConfigurationSearchQo
import com.itdct.onflow.system.configuration.vo.SysConfigurationDetailVo
import com.itdct.onflow.system.configuration.vo.SysConfigurationExportVo
import com.itdct.onflow.system.configuration.vo.SysConfigurationListVo
import com.itdct.onflow.system.file.manager.SysTransferCenterManager
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional

/**
 * @author DCTANT
 * @date 2025-09-01 14:24:40
 * @version 1.0
 * @description 系统配置服务
 */
@Service
class SysConfigurationService(
    val sysConfigurationMapper: SysConfigurationMapper,
    val sysTransferCenterManager: SysTransferCenterManager
) : BaseSysService() {

    @Transactional(rollbackFor = [Exception::class])
    fun add(qo: SysConfigurationEditQo, context: Context): RespVo<Long> {
        val addEntity = qo.toEntity(SysConfigurationEntity::class.java)
        val id = sysConfigurationMapper.insertEx(addEntity)
        return success(id)
    }

    @Transactional(rollbackFor = [Exception::class])
    fun update(qo: SysConfigurationEditQo, context: Context): RespVo<Unit> {
        val updateEntity = sysConfigurationMapper.selectByIdEx(qo.id)
        qo.injectValue(updateEntity)
        sysConfigurationMapper.updateEx(updateEntity)
        return success()
    }

    fun delete(qo: SysConfigurationEditQo, context: Context): RespVo<Unit> {
        val ids = qo.ids ?: fail(ReturnCode.LACK_PARAM, CommonString.REQUIRE_DELETE_ID_LIST)
        val deleteEntities = sysConfigurationMapper.selectByIdsEx(ids)
        sysConfigurationMapper.deleteBatchEx(deleteEntities)
        return success()
    }

    fun detail(qo: SysConfigurationSearchQo, context: Context): RespVo<SysConfigurationDetailVo> {
        val id = qo.id ?: fail(ReturnCode.LACK_PARAM, CommonString.REQUIRE_ID)
        val vo = sysConfigurationMapper.findById(id) ?: fail(CommonString.ENTITY_NOT_FOUND_USAGE("系统配置", id))
        return success(vo.dict())
    }

    fun page(qo: SysConfigurationSearchQo, context: Context): RespPageVo<SysConfigurationListVo> {
        startPage(context)
        val pageData = sysConfigurationMapper.findByList(qo)
        return successPage(pageData.dict())
    }

    fun allConfig(qo: SysConfigurationSearchQo, context: Context): RespVo<Map<String, String>> {
        val voList = sysConfigurationMapper.findByList(qo)
        val keyValueMap = HashMap<String, String>()
        for (vo in voList) {
            keyValueMap[vo.configKey!!] = vo.configValue!!
        }
        return success(keyValueMap)
    }

    fun export(qo: SysConfigurationSearchQo, context: Context): RespVo<Unit> {
        sysTransferCenterManager.export(context, "system", "系统配置", 1000L, {
            sysConfigurationMapper.findByList(qo)
        }, { listVo ->
            val exportVo = KBeanCopyUtil.copyNewInstance(listVo, SysConfigurationExportVo::class.java)
            exportVo
        })
        return success()
    }

    fun import(qo: ImportExcelQo, context: Context): RespVo<Unit> {
        val multipartFiles = qo.files ?: return error("请选择文件")
        val sysConfigurationEntities = mutableListOf<SysConfigurationEntity>()
        sysTransferCenterManager.asyncImport(context, "system", "系统配置", SysConfigurationExportVo::class.java, object : RowDataListener<SysConfigurationExportVo>() {
            override fun onRowData(data: ExcelInputRowBean<SysConfigurationExportVo>) {
                val vo = data.data
                if (vo.id != null) {
                    val id = vo.id
                    val sysConfigurationEntity = sysConfigurationMapper.selectById(id)
                    if (sysConfigurationEntity == null) {
                        checkFail("无法找到id为${id}的配置项")
                    }
                }
                vo.configKey ?: checkFail("配置键不能为空")
                vo.configValue ?: checkFail("配置值不能为空")
            }
        }, { result ->
            val dataList = result.dataList
            for (sysConfigurationExportVo in dataList) {
                val sysConfigurationEntity = KBeanCopyUtil.copyNewInstance(sysConfigurationExportVo, SysConfigurationEntity::class.java)
                sysConfigurationEntities.add(sysConfigurationEntity)
            }
        }, multipartFiles)
        sysConfigurationMapper.saveBatch(sysConfigurationEntities)
        return success()
    }

// [[ OnflowGenerator Range (- selectFunctions -) Start ]]

    fun selectConfigKeyList(qo: SysConfigurationSearchQo, context: Context): RespVo<List<KeyLabelValueVo>> {
        val vos = sysConfigurationMapper.selectConfigKeyList(qo)
        return success(vos)
    }
// [[ OnflowGenerator Range (- selectFunctions -) End ]]
}